package com.android.djlmapp.activity.my;


import android.content.Context;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.adapter.my.JiaKuanAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.dialog.JiakuanPopup;
import com.android.djlmapp.model.my.JiaKuanInfo;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.readcard.utils.LogUtils;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.refresh_view.pullrecyclerview.PullRecyclerView;
import org.refresh_view.pullrecyclerview.layoutmanager.XLinearLayoutManager;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class JiaKuanActivity extends BaseActivity {
    public static final String TAG = "djlm-my: ";

    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.jk_pull_recycler_view)
    PullRecyclerView mPullRecyclerView;

    @BindView(R.id.null_data_layout)
    RelativeLayout mNullDataLayout;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectNetErrorLayout;

    private JiaKuanAdapter mAdapter;
    private Unbinder mUnbinder;
    private Context mContext;
    private boolean isHadData = false;
    private int mPageSize = 1;
    //是否需要清空列表数据
    private boolean isClearData = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jia_kuan);
        mUnbinder = ButterKnife.bind(this);
        mContext = getActivity();

        initView();
        initData();
    }

    @Override
    protected void initView() {
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.GONE);
        tvName.setText("加款记录");

        mAdapter = new JiaKuanAdapter(this);

        mPullRecyclerView.setLayoutManager(new XLinearLayoutManager(this));
        mPullRecyclerView.setColorSchemeResources(R.color.colorAccent);
        mPullRecyclerView.setAdapter(mAdapter);
        mPullRecyclerView.enableLoadMore(false);

        mPullRecyclerView.enablePullRefresh(true);
        // 开启下拉刷新，默认即为true，可不用设置
        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {
                isClearData = true;
                isHadData = false;
                mPullRecyclerView.enableLoadMore(true);
                mPageSize = 1;

                reqInfo();
            }

            @Override
            public void onLoadMore() {
                mPullRecyclerView.enableLoadDoneTip(false, R.string.load_done_tip);
                // 开启数据全部加载完成时的底部提示，默认为false
                reqInfo();
            }
        });

        mPullRecyclerView.onRefresh();

        mAdapter.setOnItemClickListener(new JiaKuanAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(JiaKuanInfo.DataBean item) {
                JiakuanPopup.setInfo(item);
                new JiakuanPopup(mContext).showPopupWindow();
            }
        });
    }

    private void reqInfo(){
        MyApplication.getInstance().getHttpTools().jiakuan(mPageSize, mStringCallBack);
    }

    private StringCallback mStringCallBack = new StringCallback() {
        @Override
        public void onSuccess(Response<String> response) {
            LogUtils.e(TAG, "加款记录: "+response.body());

            try {
                JiaKuanInfo messageEntity = new Gson().fromJson(response.body(), JiaKuanInfo.class);
                if (messageEntity != null) {
                    List<JiaKuanInfo.DataBean> msgs = messageEntity.getData();

                    if ("200".equals("" + messageEntity.getCode()) && msgs.size() > 0) {
                        normalLayout();

                        if (isClearData) {
                            isClearData = false;
                            isHadData = false;
                            mAdapter.clear();
                            mPageSize = 1;
                        }

                        if (msgs.size() >= 10) {
                            mPageSize++;
                            mPullRecyclerView.enableLoadMore(true);
                            isHadData = true;
                        } else {
                            mPullRecyclerView.enableLoadMore(false);
                            isHadData = false;
                        }
                        mAdapter.addAll(msgs);

                    } else if ("2001".equals("" + messageEntity.getCode()) && mPageSize > 1){
                        isHadData = false;
                        mPullRecyclerView.enableLoadMore(false);
                    }else {
                        mAdapter.clear();
                        Log.i(TAG, "200 else");
                        String wanningMsg = messageEntity.getMsg();
                        showErrorLayout(false, wanningMsg);
                    }
                } else {
                    mAdapter.clear();
                    showErrorLayout(false, "服务端异常");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public void onError(Response<String> response) {
            if (mPullRecyclerView != null) {
                isClearData = false;
                showErrorLayout(true, getString(R.string.connect_sever_error_msg));
            }
        }

        @Override
        public void onFinish() {
            if (mPullRecyclerView != null) {
                mPullRecyclerView.stopLoadMore();
                mPullRecyclerView.stopRefresh();
            }
        }
    };

    @Override
    protected void initData() {}


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }

    @OnClick({R.id.ll_top_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_top_back:
                finish();
                break;

        }
    }

    /**
     * 显示布局
     * @param isNetError  是否是网络错误
     * @param warnningMsg 提示信息
     */
    private void showErrorLayout(boolean isNetError, String warnningMsg) {
        mPullRecyclerView.enableLoadMore(false);
        if (isHadData) {
            normalLayout();
            ToastUtils.showShortToastSafe(mContext, warnningMsg);
        } else {
            if (isNetError) {
                connectNetErrorLayout();
            } else {
                noDataLayout();
            }
        }
    }

    /**
     * 无数据状态
     */
    private void noDataLayout() {
        Log.i(TAG, "无数据状态");
        if (mNullDataLayout.getVisibility() == View.GONE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 网络错误状态
     */
    private void connectNetErrorLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.GONE) {
            mNullDataLayout.setVisibility(View.GONE);
            mConnectNetErrorLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 正常布局状态
     */
    private void normalLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.VISIBLE || mNullDataLayout.getVisibility() == View.VISIBLE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
        }
    }
}
